import React, { PureComponent } from 'react';
import { PropTypes } from 'prop-types';
import {
  Form, Input, Button ,Upload, Icon, Modal,message
} from 'antd';
import * as collectionService from '../service/collections';

const FormItem = Form.Item;
class Uploader extends PureComponent {
  state = {
    previewVisible: false,
    previewImage: '',
    fileList: [{
      uid: '-1',
      name: 'xxx.png',
      status: 'done',
      url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    }],
    formItemLayout:{
      labelCol: { span: 3 },
      wrapperCol: { span: 10 },
    },
    uplodItemLayout:{
      labelCol: { span: 3 },
      wrapperCol: { span: 20 },
    }
  };
  componentDidMount() {
    this.upload();
  }
  upload(){

    // if(this.props.match.params.id){
    //   collectionService.detailList(this.props.match.params.id).then(res=>{
    //     console.log(res)

    //   })
    // } else {
    //   message.error('没有ID值');
    // } 
  }
  handleCancel = () => this.setState({ 
    previewVisible: false 
  })
  handleChange = ({ fileList }) => this.setState({
   fileList 
  })
  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {

        const fileList = this.state.fileList;
        if(fileList.length>0){
          var imgurl = [];
          fileList.forEach(function(val){
            imgurl.push(val.url);
          })
          collectionService.upload({
              method:'POST',
              body: {
                info:this.state.workname,
                pic:imgurl
              }
            }).then(res=>{
            var data = res.data;
            if(data.ret_no > 0){
              message.success('发布成功！')
              this.props.history.push("/");
            }
          })
        }
      }
    });
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const { previewVisible, previewImage, fileList,formItemLayout,uplodItemLayout } = this.state;
    return (
      <div className="upload_container">
        <h3 className="work_titles">上传作品 <i></i></h3>
        <Form onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} label="作品名称">
            {getFieldDecorator('workname', {
              rules: [{
                required: true,
                message: '作品名称不能为空',
              }],
            })(
              <Input placeholder="请输入作品名称" />
            )}
          </FormItem>
          <FormItem {...uplodItemLayout} label="上传作品">
            <p className="infos">注：支持 jpg 格式，RGB 模式，单张不超过 10M（4：3比例最好，宽度1200px），最多上传 10 张，支持批量上传，（如果无法上传图片，请升级您的浏览flash版本）</p>
            <div className="clearfix">
              <Upload
                action="//jyl.bbs.360.cn/zt/360phonecyj/index.php?mod=subImg"
                listType="picture-card"
                fileList={fileList}
                withCredentials
                multiple
                onPreview={this.handlePreview}
                onChange={this.handleChange}
              >
                {fileList.length >= 100 ? null : 
                  <div>
                    <Icon type="camera" />
                    <div className="ant-upload-text">点击添加图片</div>
                  </div>
                }
              </Upload>
              <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
              </Modal>
            </div>
            <Button type="primary" htmlType="submit">发布</Button>
          </FormItem>
        </Form>

      </div>
    );
  }
}

export default Form.create()(Uploader);
